package com.darchrow.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author mdl
 * @version 1.0
 * @date 2020/9/23 9:30
 */
@Service
public class PaymentService {

    public String paymentInfo_OK(Integer id) {
        return "线程: " + Thread.currentThread().getName() + "  paymentInfo_OK, id: " + id + "\t" + "O(∩_∩)O哈哈~";
    }

    /**
     * 超时访问，降级
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
            })
    public String paymentInfo_TimeOut(Integer id) {
        // int age = 10 / 0; // a
        int timeNumber = 5; // b
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程: " + Thread.currentThread().getName() + "  paymentInfo_TimeOut, id: " + id + "\t" + "呜呜呜" + " 耗时（秒）: " + timeNumber;
    }

    public String paymentInfo_TimeOutHandler(Integer id) {
        return "o(╥﹏╥)o 调用支付服务出现异常: \t" + "\t当前线程名字: " + Thread.currentThread().getName();
    }

    // 服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求数达到多少开始计算
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 休眠时间窗口
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), // 错误率达到多少跳闸
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("*****id 不能为负数");
        }
        String simpleUUID = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号：" + simpleUUID;
    }

    public String paymentCircuitBreaker_fallback(Integer id) {
        return "id 不能为负，请稍后再试， o(╥﹏╥)o id:" + id;
    }
}
